const { app,globalShortcut,BrowserWindow,ipcMain,screen,dialog, BrowserWindowProxy,Menu,shell,remote} = require('electron');
const fs = require("fs");
const Store=require('electron-store');
const store = new Store();
store.set('title','配置文件');
store.set('msg','server:设置服务器地址如192.168.1.180:8080;packageName:包名如huasheng;updaterUrl:升级地址如192.168.1.180:8081/posUpdate');
const updaterUrl=typeof(store.get('updaterUrl'))=="undefined"?"":store.get('updaterUrl');

app.whenReady().then(() => {
    // Register a 'CommandOrControl+R' shortcut listener.
    globalShortcut.register('Ctrl+R', () => {
        win.reload();
    })

})

const customPath = app.getPath('appData')+'/'+app.name+'/custom/'
fs.mkdir(customPath, { recursive:true }, (err) => { 
    if (err) { 
        return console.error(err); 
    } 
});

const customDBPath = app.getPath('appData')+'/'+app.name+'/customDB/'
fs.mkdir(customDBPath, { recursive:true }, (err) => { 
    if (err) { 
        return console.error(err); 
    } 
});



ipcMain.on('asynchronous-message', function(event, arg ,arg1) {
    console.log("--------------------------------------")
    console.log(app.getPath('appData')+'/'+app.name+'/custom/'+arg1)
    // arg是从渲染进程返回来的数据
    //生成自定义Html
    // './html/custom_build/'
    fs.writeFile(app.getPath('appData')+'/'+app.name+'/custom/'+arg1 ,arg, "utf8",(err)=>{
        if(err){
            event.sender.send('asynchronous-reply', "写入失败" ,err);
        }else {
            event.sender.send('asynchronous-reply', "写入成功" ,err);
        }
    })
});

//打开配置文件
ipcMain.on('openConfigFile', (e)=>{
  shell.openPath(app.getPath('userData'));
});

//构建前端数据库
var Datastore = require('nedb');
    fs.unlink(app.getPath('appData')+'/'+app.name+'/hs_nedb/localStorage.db',function (err) { });
var NEDB = {}
    NEDB.test = new Datastore({ filename: app.getPath('appData')+'/'+app.name+'/customDB/test.db', autoload: true });
    NEDB.localStorage = new Datastore({ filename: app.getPath('appData')+'/'+app.name+'/hs_nedb/localStorage.db', autoload: true });

ipcMain.on('NEDB_INSERT', (e,datastore,value)=>{ 
    NEDB[datastore].insert(value, function (err, doc) {
        if (err) {
            // console.log(err);
            e.returnValue = err
        }else{
            // console.log(doc);
            e.returnValue = doc
        }
      });
});

ipcMain.on('NEDB_UPDATE', (e,datastore,arg1,arg2,arg3)=>{ 
    NEDB[datastore].update(arg1,arg2,arg3, function (err, doc) {
        if (err) {
            // console.log(err);
            e.returnValue = err
        }else{
            // console.log(doc);
            e.returnValue = doc
        }
      });
});

ipcMain.on('NEDB_REMOVE', (e,datastore,arg1,arg2)=>{ 
    NEDB[datastore].remove(arg1,arg2, function (err, doc) {
        if (err) {
            // console.log(err);
            e.returnValue = err
        }else{
            // console.log(doc);
            e.returnValue = doc
        }
      });
});

ipcMain.on('NEDB_FIND', (e,datastore,find={},sort={},skip='',limit='')=>{ 
    NEDB[datastore].find(find).sort(sort).skip(skip).limit(limit).exec(function(err, doc){
        if (err) {
            // console.log(err);
            e.returnValue = err
        }else{
            // console.log(doc);
            e.returnValue = doc
        }
    });
});

ipcMain.on('NEDB_COUNT', (e,datastore,arg1={})=>{ 
    NEDB[datastore].count(arg1, function (err, doc) {
        if (err) {
            // console.log(err);
            e.returnValue = err
        }else{
            // console.log(doc);
            e.returnValue = doc
        }
      });
});



//构建内存数据库
// var loki = require('lokijs');
// var db = new loki('StorageLoki',{
//   persistenceMethod:"localStorage"
// });

// var StorageLokiCollect = db.addCollection('StorageLokiCollect',{unique: ['key'],asyncListeners:false});
// ipcMain.on('getItem', (e,key)=>{ 
//   let getItemData=StorageLokiCollect.find({'key':key});
//   e.returnValue=getItemData;
// });
// ipcMain.on('setItem', (e,key,value)=>{
//   let getItemData=StorageLokiCollect.find({'key':key});
//   if(getItemData.length>0)
//     StorageLokiCollect.findAndRemove({'key':key});
//   StorageLokiCollect.insert({'key':key,'value':value});
// });
// ipcMain.on('removeItem', (e,key)=>{ 
//   e.returnValue=StorageLokiCollect.findAndRemove({'key':key});
// });

ipcMain.on('getItem', (e,key)=>{ 
    NEDB['localStorage'].find({ 'key': key }, function (err, doc) {
        if (err) {
            e.returnValue = err
        }else{
            e.returnValue = doc
        }
    });
});
ipcMain.on('setItem', (e,key,value)=>{
    NEDB['localStorage'].find({ 'key': key }, function (err, docs) {
        // console.log(docs)
        // console.log(docs.length)
        // console.log(JSON.stringify(docs))
        if (err) {
            
        }else{
            if(docs.length>0){
                NEDB['localStorage'].remove({ 'key': key }, { multi: true }, function (err, numRemoved) {
                    NEDB['localStorage'].insert({'key':key,'value':value}, function (err, doc) {
                        if (err) {
                            e.returnValue = err
                        }else{
                            e.returnValue = doc
                        }
                    });
                });
            }else{
                NEDB['localStorage'].insert({'key':key,'value':value}, function (err, doc) {
                    if (err) {
                        e.returnValue = err
                    }else{
                        e.returnValue = doc
                    }
                });
            }
        }
    });
});
ipcMain.on('removeItem', (e,key)=>{ 
    NEDB['localStorage'].remove({ 'key': key }, { multi: true }, function (err, numRemoved) {

    });
//   e.returnValue=StorageLokiCollect.findAndRemove({'key':key});
});

//判断是否多开进程
ipcMain.on('isMultiProgramming', (e)=>{ 
  const gotTheLock = app.requestSingleInstanceLock();
  e.returnValue=gotTheLock;
});

ipcMain.on('testDo', ()=>{ 
  console.time()
});
ipcMain.on('testDoEnd', ()=>{ 
  console.timeEnd();
});

//保存配置信息
ipcMain.on('saveConfigMess', (e,mess,reload=true)=>{
  store.set('server',mess.server||"");
  store.set('packageName',mess.packageName||"");
  store.set('updaterUrl',mess.updaterUrl||"");
  store.set('fullscreen',mess.fullscreen||"");
  store.set('hotelID',mess.hotelID||"");
  store.set('bmh',mess.bmh||"");
  store.set('his_bmh',mess.his_bmh||"");
  store.set('his_hotelID',mess.his_hotelID||"");
  if(reload){
    dialog.showMessageBox(win, {
      type: 'warning',
      title: '提示',
      message: '配置保存成功！',
      buttons: ['知道了']
    }).then((index) => {
      app.exit();
      app.relaunch();
    });
  }
});

//试运行窗口
ipcMain.on('openTest', (e,urlpath)=>{
  let winTest = new BrowserWindow({});
  winTest.loadURL(urlpath);
});

//窗体关系
let windowsOpen = new Array();
//当前主进程
let win=null;
//更新状态
const updateStateText={
  DOWNLOADING:'正在下载',
  UPDATEWILL:'准备更新',
  NORMAL:'无需更新'
}
let updateState=updateStateText.NORMAL;

//----------------创建窗口开始---------------------------
function createWindow () {   
  let size = screen.getPrimaryDisplay().workAreaSize;
  win = new BrowserWindow({
    width:size.width,
    height:size.height,
    skipTaskbar:false,
    fullscreen:store.get('fullscreen')=="op"?true:false,
    show: false,
    icon : "images/packagee32.png",
    webPreferences: {
      nodeIntegration: true,
      nodeIntegrationInWorker: false,
      enableRemoteModule:true
    }
  });

  if(!win.isFullScreen())
    win.maximize();
  Menu.setApplicationMenu(null);

  win.loadFile('./html/login/login.html');

  ipcMain.on('setLoginMenu', (e)=>{
    Menu.setApplicationMenu(null);
    let templateLogin=new Array();
    templateLogin.push({
      label:'调试',
      submenu:[{
        label:'DevTools',
        accelerator:'Ctrl+Shift+I',
        role:'toggleDevTools'
      },{
        label:'刷新',
        accelerator:'F5', 
        role:'forceReload'
      },{
        label:'版本信息',
        click:function(){
          dialog.showMessageBox(win, {
            type: 'warning',
            title: '版本信息',
            message: '当前版本:'+ require("./package.json").version,
            buttons: ['知道了']
          }).then((index) => {
            dialog.close();
          });
        },
      }]
    });
    var menu = Menu.buildFromTemplate(templateLogin);
    win.autoHideMenuBar=true;
    win.menuBarVisible=false;
    win.setMenu(menu);
  });

  win.show();
  //主进程窗体大小改变
  // win.on('resize',(e)=>{
  //   if(updateState!=updateStateText.NORMAL)
  //     return;
  //   win.reload();
  // });

  //主进程菜单
  ipcMain.on('creMainMenu', (e, menu_json,depMenu_json)=>{
    let template=new Array();
    template.push({
        label:'首页',
        click:function(){
            win.webContents.send('menuClick','#/html/homepage/homepage.html');
        },
    })   
    // template.push({
    //     label:'上一页',
    //     click:function(){

    //     },
    // })
    // template.push({
    //     label:'下一页',
    //     click:function(){
            
    //     },
    // })

		if(menu_json.hasOwnProperty('0')){
      for(item in menu_json['0']){
        let value=menu_json['0'][item];
				let templateItem={};
				let menuCode=(value.menu_code||'');
				let menuName=(value.menu_name||'');
				let submenuData=(menu_json[menuCode]||new Array());
        let submenu=new Array();
        for(k in submenuData){
          let v=submenuData[k];
					let submenuItem={};
          submenuItem.label=(v.menu_name||'');
          var path ="images/"+v.menu_name+".png";

          //校验是否
          try {
            fs.realpathSync(path);
            submenuItem.icon=path;
          } catch(e){
            submenuItem.icon="";
          }

					submenuItem.click=function(){

                        var href = ''
                        if(v.data_url.indexOf('?&') >= 0){
                            href = '#/'+v.data_url+'&arg='+v.menu_code.trim()+'&pmenucode='+v.parent_menucode+''
                        }else{
                            href = '#/'+v.data_url+'?&arg='+v.menu_code.trim()+'&pmenucode='+v.parent_menucode+''
                        }
                        
						  win.webContents.send('menuClick',href);
					}
					submenuItem.accelerator=(v.quickKey||'');
					submenu.push(submenuItem);
					submenu.push({type:'separator'});
				}
        templateItem.label=menuName;
        templateItem.submenu=submenu;
				template.push(templateItem);
			}
    }

    let depMenus=[];
    for(item in depMenu_json){
      let itemSubMenu={};
      itemSubMenu.label=depMenu_json[item].bh+depMenu_json[item].mc;
      let dep=depMenu_json[item].bh;
      itemSubMenu.click=function(){
        win.webContents.send('changeDep',dep);
      }
      depMenus.push(itemSubMenu);
    }

    template.push({
      label:'关于',
      submenu:[
        // {
        //   label:'部门',
        //   submenu:depMenus
        // },
        {
          label:'DevTools',
          accelerator:'Ctrl+Shift+I',
          role:'toggleDevTools'
      },{
        label:'刷新',
        accelerator:'F5', 
        role:'forceReload'
      },{
        label:'版本信息',
        click:function(){
          dialog.showMessageBox(win, {
            type: 'warning',
            title: '版本信息',
            message: '当前版本:'+ require("./package.json").version,
            buttons: ['知道了']
          }).then((index) => {
            dialog.close();
          });
        },
      },{
        label:'触屏版',
        click:function(){
          try {
            let needCloseWindows=getOpenWindowsByParent(win.id);
            for(let i=0;i<needCloseWindows.length;i++){
              BrowserWindow.fromId(needCloseWindows[i]).close();
            }
          } catch (error) {
            console.log(error)
          }
          win.loadFile('./indexFullScreen.html');
        },
      }]
    });

    var menu = Menu.buildFromTemplate(template);
    win.autoHideMenuBar=false;
    win.menuBarVisible=true;
    Menu.setApplicationMenu(null);
    win.setMenu(menu);

    if(win.isFullScreen()){
      win.setFullScreen(false);
      win.maximize();
    }
    
    store.set('fullscreen','pc');
  });

  //触屏模式
  ipcMain.on('setApplicationMenu', (e)=>{ 
    let template=new Array();
    template.push({
      label:'调试',
      submenu:[{
        label:'DevTools',
        accelerator:'Ctrl+Shift+I',
        role:'toggleDevTools'
      },{
        label:'刷新',
        accelerator:'F5', 
        role:'forceReload'
      },{
        label:'版本信息',
        click:function(){
          dialog.showMessageBox(win, {
            type: 'warning',
            title: '版本信息',
            message: '当前版本:'+ require("./package.json").version,
            buttons: ['知道了']
          }).then((index) => {
            dialog.close();
          });
        },
      }]
    });
    var menu = Menu.buildFromTemplate(template);
    win.autoHideMenuBar=true;
    win.menuBarVisible=false;
    Menu.setApplicationMenu(null);
    win.setMenu(menu);
    win.setFullScreen(true);
    store.set('fullscreen','op');
  });


  //获取配置信息
  ipcMain.on('getConfigMess', (e)=>{ 
      let configValue={};
      configValue.HSAPI_SERVER=typeof(store.get("server"))=="undefined"?'':store.get("server");
      configValue.HSAPI_PACKAGENAME=typeof(store.get("packageName"))=="undefined"?'':store.get("packageName");
      configValue.HSAPI_UPDATERURL=typeof(store.get("updaterUrl"))=="undefined"?'':store.get("updaterUrl");
      configValue.HSAPI_FULLSCREEN=typeof(store.get("fullscreen"))=="undefined"?'':store.get("fullscreen");
      configValue.HSAPI_HOTELID=typeof(store.get("hotelID"))=="undefined"?'':store.get("hotelID");
      configValue.HSAPI_BMH=typeof(store.get("bmh"))=="undefined"?'':store.get("bmh");
      configValue.his_hotelID=typeof(store.get("his_hotelID"))=="undefined"?'':store.get("his_hotelID");
      configValue.his_bmh=typeof(store.get("his_bmh"))=="undefined"?'':store.get("his_bmh");
      configValue.appCustomPath = app.getPath('appData')+'/'+app.name+'/custom/';
      e.returnValue=configValue;
      // console.log()
  });
  
  //关闭除了主窗体的其余窗体
  ipcMain.on('coloseWins', (e, arg)=>{
    let needCloseWindows=getOpenWindowsByParent(win.id);
      for(let i=0;i<needCloseWindows.length;i++){
        BrowserWindow.fromId(needCloseWindows[i]).close();
      }
  });

  //关闭窗体且跳转到登录页面
  ipcMain.on('coloseWinsToLogin', (e, arg)=>{
    let needCloseWindows=getOpenWindowsByParent(win.id);
    for(let i=0;i<needCloseWindows.length;i++){
      BrowserWindow.fromId(needCloseWindows[i]).close();
    }
    win.loadFile('./html/login/login.html');
  });
  
  //导出excel
  ipcMain.on('downloadExcelFile', (e, url) => {
    win.webContents.downloadURL(url);
  });
  
  //关闭主进程
  ipcMain.on('closeMainExe', (e, url) => {
    app.exit();
  });
  
  //关闭主进程
  win.on('close',(e)=>{
      if(updateState==updateStateText.UPDATEWILL)
        return;
      e.preventDefault();
      dialog.showMessageBox(win, {
          type: 'warning',
          title: '关闭',
          message: '是否退出？',
          buttons: ['取消', '确定']
      }).then((index) => {
          if (index.response === 1) {
              win = null;
              app.exit();
          }
      });
  })

  //主进程关闭
  win.on('closed',(e)=>{
    app.quit();
  });

  //主进程最小化
  win.on('minimize',()=>{
    let allWindows=BrowserWindow.getAllWindows();
    for(let i=0;i<allWindows.length;i++){
      allWindows[i].minimize();
    }
  });
  win.show();

  //窗体崩溃处理
  breakdown(win);

  //配置更新
  if(updaterUrl!=""&&updaterUrl!='http://'&&updaterUrl!='https://')
    updateHandle();
  
  //打开新窗口
  ipcMain.on('newWindow',(e,url,params={},options={})=>{
    let isOpen=isOpenWindow(url+options.hash);
    if(isOpen!=''){
      let openWindow=BrowserWindow.fromId(isOpen);
      openWindow.show();
      return;
    }

    let newWin;
    let y=win.isFullScreen()?win.getPosition()[1]+params.top+10:win.getPosition()[1]+params.top+40;
    newWin = new BrowserWindow({
      title:params.title,
      width: (params['width'] && params['width']!='')?params['width']:win.getSize()[0], 
      height: (params['height'] && params['height']!='')?params['height']:win.getSize()[1]-params.top-50,
      x:(params['center'] && params['center']=='yes')?null:win.getPosition()[0]+params.left,
      y:(params['center'] && params['center']=='yes')?null:y,
      fullscreen:false,
      autoHideMenuBar:true,
      modal:false,
      show:false,
      center:true,
      parent:params.parent?win:'',
      skipTaskbar:false,
      icon : "images/f&b.png",
      webPreferences: {
        nodeIntegration: true,
        nodeIntegrationInWorker: false,
        enableRemoteModule:true
      }
    });

    //菜单
    let template=new Array();
    template.push({
      label:'调试',
      submenu:[{
        label:'DevTools',
        accelerator:'Ctrl+Shift+I',
        role:'toggleDevTools'
      },{
        label:'刷新',
        accelerator:'F5', 
        role:'forceReload'
      },{
        label:'关闭',
        accelerator:'ESC', 
        click:function(){
          dialog.showMessageBox(newWin, {
            type: 'warning',
            title: '关闭',
            message: '是否退出['+params.title+']？',
            buttons: ['关闭', '取消']
          }).then((index) => {
            if (index.response === 1) {
              return;
            }else 
              newWin.close();
          });
        }
      },{
        label:'版本信息',
        click:function(){
          dialog.showMessageBox(win, {
            type: 'warning',
            title: '版本信息',
            message: '当前版本:'+ require("./package.json").version,
            buttons: ['知道了']
          }).then((index) => {
            dialog.close();
          });
        },
      }]
    });

    var menu = Menu.buildFromTemplate(template);
    newWin.setMenu(menu);

    windowsOpen.push({'uuid':newWin.id,'url':url+options.hash,'parentId':params.parentId});
    newWin.loadFile(url,options);
    newWin.webContents.on('did-finish-load', function(){
      newWin.show();
      newWin.webContents.send('dataJsonPort', params);
      let windowOpenParams={'oper':'newWindow','title':params.title,'menuCode':params.menuCode,'parentMenuCode':params.parentMenuCode};
      win.webContents.send('windowOper',windowOpenParams);
    });
    let winId=newWin.id;

    newWin.on('close',()=>{
      let windowOpenParams={'oper':'closeWindow','title':params.title,'menuCode':params.menuCode,'parentMenuCode':params.parentMenuCode};
      win.webContents.send('windowOper',windowOpenParams);

      newWin=null;
      let needCloseWindows=getOpenWindowsByParent(winId);
      for(let i=0;i<needCloseWindows.length;i++){
        BrowserWindow.fromId(needCloseWindows[i]).close();
        closeOpenWindow(needCloseWindows[i]);
      }
      closeOpenWindow(winId);
      if(windowsOpen.length==0)
          win.show();
    });
    
    //窗口还原
    newWin.on('restore',()=>{
      let needreStoreWindows=getOpenWindowsByChild(winId);
      for(let i=0;i<needreStoreWindows.length;i++){
        BrowserWindow.fromId(needreStoreWindows[i]).restore();
      }
    });

    //窗体崩溃处理
    breakdown(newWin);

  });

  //打开新模态
  ipcMain.on('newModal',(e,hash,params={},frame=true)=>{
    let parentId=params.parentId;
    newModal = new BrowserWindow({
      title:params.title,
      width: params.hasOwnProperty("width")?params.width:800,
      height: params.hasOwnProperty("height")?params.height:600,
      modal:true,
      center:true,
      frame:frame,
      autoHideMenuBar : true,
      icon : "images/f&b.png",
      parent:BrowserWindow.fromId(parentId),
      webPreferences: {
        nodeIntegration: true,
        nodeIntegrationInWorker: false,
        enableRemoteModule:true
      }
    });

    //菜单
    let template=new Array();
    template.push({
      label:'调试',
      submenu:[{
        label:'DevTools',
        accelerator:'Ctrl+Shift+I',
        role:'toggleDevTools'
      },{
        label:'刷新',
        accelerator:'F5', 
        role:'forceReload'
      },{
        label:'版本信息',
        click:function(){
          dialog.showMessageBox(win, {
            type: 'warning',
            title: '版本信息',
            message: '当前版本:'+ require("./package.json").version,
            buttons: ['知道了']
          }).then((index) => {
            dialog.close();
          });
        },
      }]
    });

    var menu = Menu.buildFromTemplate(template);
    newModal.setMenu(menu);

    newModal.loadFile('./indexWindow.html',hash);
    newModal.webContents.on('did-finish-load', function(){
      newModal.webContents.send('dataJsonPort', params);
    });
    newModal.on('closed', () => {
      newModal = null
    })

    //模态还原
    newModal.on('restore',()=>{
      let winId=newModal.getParentWindow().id;
      let needreStoreWindows=getOpenWindowsByChild(winId);
      for(let i=0;i<needreStoreWindows.length;i++){
        BrowserWindow.fromId(needreStoreWindows[i]).restore();
      }
    });

    //窗体崩溃处理
    breakdown(newModal);
  });
}

//----------------创建窗口结束---------------------------

//----------------对窗口的逻辑开始-----------------------
//是否已打开过窗口
function isOpenWindow(v){
  let isOpenValue='';
  for(let i=0;i<windowsOpen.length;i++){
    let item=windowsOpen[i];
    if(item.url==v){
      isOpenValue=item.uuid;
      break;
    }
  }
  return isOpenValue;
}
//关闭窗口
function closeOpenWindow(v){
  let nowOpenWindow=new Array();
  for(let i=0;i<windowsOpen.length;i++){
    let item=windowsOpen[i];
    if(item.uuid!=v){
      nowOpenWindow.push(item);
    }
  }
  windowsOpen=nowOpenWindow;
}
//当前窗口所有关联子孙
function getOpenWindowsByParent(id,result=[]){
    for(let i=0;i< windowsOpen.length;i++){
      let item=windowsOpen[i];
      if(item.parentId==id){
        result.push(item.uuid);
        getOpenWindowsByParent(item.uuid,result);
      }
    }
    return result;
}

//当前窗口所有祖先
function getOpenWindowsByChild(id,result=[]){
  for(let i=0;i< windowsOpen.length;i++){
    let item=windowsOpen[i];
    if(item.uuid==id){
      result.push(item.parentId);
      getOpenWindowsByChild(item.parentId,result);
    }
  }
  return result;
}

//窗体崩溃处理
function breakdown(_win){
  _win.webContents.on('crashed', function () {
    dialog.showMessageBox(_win, {
      type: 'warning',
      title: '关闭',
      message: '是否退出？',
      buttons: ['重载', '关闭']
    }).then((index) => {
      if (index.response === 0) {
        _win.reload();
      }else 
        _win.close();
    });
  });
}
//----------------对窗口的逻辑结束-----------------------

//-----------控制应用程序的事件生命周期-------------------
app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
    app.quit()
})
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})
//-----------控制应用程序的事件生命周期-------------------

//------------------配置更新----------------------------
const { autoUpdater} = require('electron-updater');
//配置更新
function updateHandle() {
  autoUpdater.setFeedURL(updaterUrl);
  autoUpdater.autoDownload = false;
  //检查更新出错
  autoUpdater.on('error', function (error) {
    sendUpdateMessage('-1',error)
  });
  //正在检查更新
  autoUpdater.on('checking-for-update', function () {
    sendUpdateMessage('正在检查更新')
  });
  //有更新
  autoUpdater.on('update-available', function (info) {
    sendUpdateMessage('1',info)
  });
  //无需更新
  autoUpdater.on('update-not-available', function (info) {
    sendUpdateMessage('无需更新')
  });
  //下载
  ipcMain.on('downloadUpdate', (e, arg)=>{
    if(arg==0)
      updateState=updateStateText.DOWNLOADING;
    autoUpdater.downloadUpdate();
  });
  //下载进度
  autoUpdater.on('download-progress', function (progressObj) {
    win.webContents.send('downloadProgress', progressObj)
  })
  //下载完成
  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
    ipcMain.on('isUpdateNow', (e, arg)=>{
      //执行更新
      updateState=updateStateText.UPDATEWILL;
      autoUpdater.quitAndInstall();
    });
    win.webContents.send('isUpdateNow')
  });
  ipcMain.on("checkForUpdate",()=>{
      autoUpdater.checkForUpdates();
  })
}
//返回更新信息
function sendUpdateMessage(text,info={}) {
  win.webContents.send('message', text,info)
}
//------------------配置更新结束--------------------------

